package org.example.service;

import org.example.pojo.User;
import org.example.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 荆延龙
 * @version 1.0.0
 * data 2022/06/12
 */
@Service
@Configuration
public class UserService {
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    UserRepository userRepository;

    public void saveNewUser(User user) throws Exception {
        if (userRepository.findByUname(user.getUname()).orElse(null)!=null) throw new Exception("用户名已存在！");
        user.setPword(passwordEncoder.encode(user.getPword()));
        user.setRole(user.getRole().toUpperCase());
        if (!user.getRole().equals("ADMIN") && !user.getRole().equals("USER")) throw new Exception(user.getRole()+"权限不存在！");
        userRepository.saveAndFlush(user);
    }
    public void changeUserInfo(User user) throws Exception {
        User u = userRepository.findByUname(user.getUname()).orElse(null);
        if (u==null) throw new Exception("用户不存在！");
        if (!BCrypt.checkpw(user.getOpword(), u.getPword())) throw new Exception("请输入正确的密码！");
        u.setPword(passwordEncoder.encode(user.getPword()));
        userRepository.saveAndFlush(u);
    }
    public List<User> findAllUser(){
        return userRepository.findAll();
    }
    public void deleteUser(User user) throws Exception{
        User u = userRepository.findByUname(user.getUname()).orElse(null);
        if (u==null) throw new Exception("用户不存在！");
        if (!BCrypt.checkpw(user.getOpword(), u.getPword())) throw new Exception("请输入正确的密码！");
        userRepository.deleteById(u.getId());
    }
}
